import React from 'react'
import { useAppSelector } from '../../app/hooks'
import { Button, Uploader } from 'react-vant'
import { useNavigate } from 'react-router-dom'
const Index = () => {
	const isLogin = useAppSelector(state => state.user.isLogin)
	const avator = useAppSelector(state => state.user.avator)
	const nickname = useAppSelector(state => state.user.nickname)
	const token = useAppSelector(state => state.user.token)
	const id = useAppSelector(state => state.user.id)
	const navigate = useNavigate()

	// 实际业务中需要自己实现对应上传逻辑
	const upload = async (file: File) => {
		try {
			const body = new FormData()
			body.append('source', file)
			body.append('id', id)
			const resp = await fetch('/api/upload', {
				method: 'POST',
				body,
			})
			const json = await resp.json()
			console.log(json);
			// return包含 url 的一个对象 例如: {url:'https://img.yzcdn.cn/vant/sand.jpg'}
			return json.data
		} catch (error) {
			return { url: `demo_path/${file.name}` }
		}
	}
	return (
		<div>
			{
				isLogin
					? (
						<div>
							{avator ? <img src={avator} alt="" /> : <Uploader upload={upload} />}
							<h3>{nickname}</h3>
						</div>
					)
					: (
						<div>
							<Button type="primary" onClick={() => navigate('/login')}>去登录</Button>
						</div>
					)
			}
		</div>
	)
}

export default Index